import { createRouter, createWebHistory,RouteRecordRaw } from 'vue-router'
import store from '@/store';

const routes : Array<RouteRecordRaw>= [
  {
    path: '/login',
    name: 'login',
    component: () => import('../common/login/index.vue')
  },
  {
    path: '/noPermission',
    name: 'noPermission',
    component: () => import('../common/noPermission/index.vue')
  },
  {
    path: '/',
    name: 'index',
    component: () => import('@/common/index/index.vue'),
    children: []
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../common/404/index.vue'),
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  }
]
const noneloginRequired = ['/login','/noPermission','/404'];//无需登录页面集合，可扩展

const router = createRouter({
  history: createWebHistory('/web'),
  routes
})

/**
 * 获取第一个菜单
 * 后面改成栈的算法，先用嵌套吧，层级也不高
 * @param menu
 * @returns {*}
 */
const getChildFirst = (menu:any)=>{
  let url = '';
  if (menu.childList && menu.childList.length > 0) {
    url = getChildFirst(menu.childList[0])
  }else{
    url = menu.url;
  }
  return url
}

router.beforeEach(async function (to, from, next) {
  if (!noneloginRequired.includes(to.path)) {
    if (!sessionStorage.upmSessionId) {
      if (!localStorage.sessionStorage) {
        next('/login');
        return false;
      }
      sessionStorage.upmSessionId = localStorage.sessionStorage;
      //当前为其他系统跳转过来的，根据Session获取用户信息
      try {
        await store.dispatch('userMessage/getLoginUser');
      } catch (e) {
        next('/login');
      }
      let timer = setTimeout(() => {
        localStorage.removeItem('sessionStorage')
        clearTimeout(timer);
      }, 1000 * 30)
    }
  }

  //跳转过来有session的情况
  if (router.getRoutes().length <=5 && sessionStorage.upmSessionId){
    try {
      await store.dispatch('userMessage/getLoginUser');
    } catch (e) {
      next('/login');
    }
  }

  //登录后没有页面去首页 || 有了权限不能再走登录，必须登出才可以换账号
  if (to.path === "/" || (to.path === "/login" && sessionStorage.upmSessionId)) {
    let menu = store.getters['userMessage/getMenuList'];
    let firstPage = menu[0] ? getChildFirst(menu[0]) : 'simulationOperation';
    next('/' + firstPage);
    return false;
  }

  //navigation的数据
  let navMenu = sessionStorage.boardMenu ? JSON.parse(sessionStorage.boardMenu) : [];
  let index = navMenu.findIndex((item: { name: string; }) => item.name === to.path.split('/')[1]);
  if (index === -1 && to.meta.title) {
    navMenu.push({title: to.meta.title, name: to.path.split('/')[1]})
    sessionStorage.boardMenu = JSON.stringify(navMenu);//标题
  }
  store.dispatch('boardMenu/setRouters', navMenu);
  next();
  //重置左右侧按钮的值
  store.commit('boardControl/resetState');
})

export default router
